package com.shimao.celnet.payment.controller.api;

import com.shimao.celnet.payment.form.BEstateForm;
import com.shimao.celnet.payment.model.BEstate;
import com.shimao.celnet.payment.model.PPay;
import com.shimao.celnet.payment.model.PPayDetail;
import com.shimao.celnet.payment.model.request.CallIn_outPayResultRequest;
import com.shimao.celnet.payment.model.request.CallIn_outPayResultRequestPayDetails;
import com.shimao.celnet.payment.model.request.CallIn_outPayResultRequestPays;
import com.shimao.celnet.payment.model.response.ErrorInfoEnum;
import com.shimao.celnet.payment.model.response.ResponseJson;
import com.shimao.celnet.payment.service.BEstateService;
import com.shimao.celnet.payment.service.BHouseService;
import com.shimao.celnet.payment.service.PPayDetailService;
import com.shimao.celnet.payment.service.PPayService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.MyDateUtil;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

/**
 * 2018/01/05
 * christ
 * 外部系统 → 支付系统，【数据】：业务系统没有通过支付平台，完成收款数据，凌晨批量推送
 */
@RestController
@RequestMapping("/batch")
public class CallIn_outPayResultReqInController {
    protected Logger logger = Logger.getLogger(this.getClass());
    @Autowired//支付申请
    private PPayService pPayService;

    @Autowired //支付明细
    private PPayDetailService pPayDetailService;

    @Autowired//房间
    private BHouseService bHouseService;

    @Autowired//小区
    private BEstateService bEstateService;

    @ApiOperation("获取外部批量推送数据数据")
    @RequestMapping(value = "/push", method = RequestMethod.POST)
    public String resultBatchPush(@RequestBody @Valid CallIn_outPayResultRequest callIn_outPayResultRequest, BindingResult result) {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        ResponseJson retJson = new ResponseJson(ErrorInfoEnum.SUCCESS, "");
        //界面输入验证
        if (result.hasErrors()) {
            for (FieldError error : result.getFieldErrors()) {
                logger.debug("缺少必要参数：" + error.getDefaultMessage());
                retJson = new ResponseJson(ErrorInfoEnum.NOT_PARAMS, error.getDefaultMessage());
                return retJson.toString();
            }
        }
        /**
         * 1， 存储数据，并记录存储条数，视为正常推送条数
         */
        //记录成功的数据，按照<K,V>--<payId,guid>
        TreeMap<String, String> retMap = new TreeMap<String, String>();
         //创建时间
        String createDate = MyDateUtil.DateToStr(new Date(),MyDateUtil.format_yyyy_MM_dd);
        //保存集合
        List<PPay> saveList = new ArrayList<>();
        //保存明细数据
        List<PPayDetail> pPayDetailList = new ArrayList<PPayDetail>();
        //取得订单数据
        List<CallIn_outPayResultRequestPays> requestJsonList = callIn_outPayResultRequest.getPayList();
        for (CallIn_outPayResultRequestPays RequestPays : requestJsonList) {
            PPay pPay = new PPay();
            //如果支付金额为0时,视为脏数据，不做保存记录
          if(!"0".equals(RequestPays.getPayAmount())){
              //1.根据外部系统只支付id，进行去重复删除支付记录和支付明细
              pPayService.deleteByPayId(RequestPays.getPayId(),RequestPays.getEstateId(),createDate);
              BEstateForm estate = bEstateService.getBySfGuid(RequestPays.getEstateId());
              //2.插入新数据  --如果在小区表里面没有查询到改小区，那么就不保存到数据库
              if(estate != null) {
                  String payGuid = pPayService.getGuid();//自动生成guid
                  pPay.setGuid(payGuid);
                  pPay.setCreatedUserGuid(FinalUtil.INTER_FACE_USER_ID);
                  pPay.setUpdateUserGuid(FinalUtil.INTER_FACE_USER_ID);
                  pPay.setExsysPayId(RequestPays.getPayId()); //外部支付系统id
                  pPay.setBusinessType(RequestPays.getPayBusinessType());    //	业务类型
                  pPay.setPayAmount(RequestPays.getPayAmount());    //	支付金额
                  pPay.setPayStartTime(String.valueOf(System.currentTimeMillis()));//	支付开始时间
                  pPay.setPayEndTime(String.valueOf(MyDateUtil.StrToDate(RequestPays.getPaytime(), MyDateUtil.format_yyyyMMddHHmmss).getTime()));//	支付开始时间
                  pPay.setEstateGuid(estate.getGuid());    //	小区guid
                  pPay.setEstateSfGuid(RequestPays.getEstateId());    //	小区SF-GUID
                  //pPay.setHourceGuid(bHouseService.getBySfGuid(RequestPays.getHouseId()).getGuid());    //	支付房间guid
                  // pPay.setHourceSfGuid(RequestPays.getHouseId());    //	支付房间SF-GUID
                  //pPay.setPayUserSfGuid(RequestPays.getUserId());    //	支付用户SF-GUID
                  // pPay.setPayUserName(RequestPays.getUserName());    //	支付用户名称
                  pPay.setPayRemark(RequestPays.getPayRemark());    //	支付说明
                  pPay.setPayType(RequestPays.getPayType());  //支付类型
                  pPay.setPayStatus(FinalUtil.PAY_STATUS_SUSCSS);//支付状态
                  pPay.setAppKey(request.getHeader(FinalUtil.HEADER_APP_KEY));//app_key
                  pPay.setInterfaceId(request.getHeader(FinalUtil.HEADER_INTERFACE_ID));//接口id
                  //取得支付明细
                  List<CallIn_outPayResultRequestPayDetails> paymentList = RequestPays.getPayDetailList();
                  for (CallIn_outPayResultRequestPayDetails payment : paymentList) {
                      PPayDetail pPayDetail = new PPayDetail();
                      pPayDetail.setExsysDetailId(payment.getPayDetailId());//外部系统明细id
                      pPayDetail.setAmount(payment.getPayDetailAmount());//明细金额
                      pPayDetail.setRemark(payment.getPayDetailRemark());//明细说明
                      pPayDetail.setpPayGuid(payGuid);
                      pPayDetail.setGuid(pPayDetailService.getGuid()); //增加id
                      pPayDetail.setCreatedUserGuid(FinalUtil.INTER_FACE_USER_ID);
                      pPayDetail.setUpdateUserGuid(FinalUtil.INTER_FACE_USER_ID);
                      //支付申请记录明细保存
                      pPayDetailList.add(pPayDetail);
                  }
                  saveList.add(pPay);



                  /**
                   * 2， 记录正常推送数据的payid和支付系统guid
                   */
                  //把插入成功的数据，按照<K,V>--<payId,guid>
                  retMap.put(RequestPays.getPayId(), payGuid);
              }
          }
        }
        //批量增加支付记录
        pPayService.saveByList(saveList);
        //批量增加支付明细记录
        pPayDetailService.saveByBatchList(pPayDetailList);
        /**
         * 3，返结果通知
         */
        retJson.addBody("payRetList", JSONArray.fromObject(retMap));
        return retJson.toString();
    }
}

